package com.sunwayworld.basemodule.rm.environment.io;

import com.sunwayworld.baseline.framework.override.LimsExcelHelper;
import com.sunwayworld.basemodule.rm.environment.bean.LimsEnvironmentDataBean;
import com.sunwayworld.basemodule.rm.environment.bean.LimsEnvironmentRoomBean;
import com.sunwayworld.basemodule.rm.environment.service.LimsEnvironmentDataService;
import com.sunwayworld.basemodule.rm.environment.service.LimsEnvironmentRoomService;
import com.sunwayworld.basemodule.rm.material.bean.LimsMaterialBean;
import com.sunwayworld.basemodule.rm.material.service.LimsMaterialService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.framework.utils.NumberUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.bean.CoreFileImportResultDTO;
import com.sunwayworld.module.item.file.function.CoreFileImportFunction;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiongym 2020年4月15日
 */
@Component(value = "LimsEnvironmentRoomImportFileFunction")
@GikamBean
public class LimsEnvironmentRoomImportFileFunction implements CoreFileImportFunction {


    @Autowired
    @Lazy
    private LimsEnvironmentRoomService limsEnvironmentRoomService;

    @Autowired
    @Lazy
    private LimsEnvironmentDataService limsEnvironmentDataService;

    @Autowired
    @Lazy
    private CoreCodeService coreCodeService;

    @Override
    @Transactional
    public CoreFileImportResultDTO apply(CoreFileBean coreFileBean) {
        CoreFileImportResultDTO importResultRepresentation = new CoreFileImportResultDTO();
        FilePathDTO fr = CoreFileUtils.toFilePath(coreFileBean);
        List<LimsEnvironmentRoomBean> environmentRoomBeans = LimsExcelHelper.readDataFromExcel(FilePathManager.getLocalPath(fr).toString(), 1, 2, LimsEnvironmentRoomBean.class);
        if (CollectionUtils.isEmpty(environmentRoomBeans)) {
            throw new InvalidDataException("导入表格非法！");
        }

        List<String> columns = Arrays.asList("roomCode", "roomName", "time");
        List<String> colNames = Arrays.asList("【房间号】", "【房间名称】", "【记录时间】");
        environmentRoomBeans.forEach(a -> {
            StringBuilder msg = new StringBuilder();
            for (int i = 0; i < columns.size(); i++) {
                Object value = BeanUtils.getPropertyValue(a, columns.get(i));
                if (value == null || (value.getClass().equals(String.class) && value.equals(""))) {
                    msg.append(colNames.get(i));
                }
            }
            if (msg.length() > 0) {
                msg.append(" 为必填项；");
            }
            if (msg.length() > 0) {
                if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                    a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat(msg.toString()));
                } else {
                    a.setExt$Item("validateimpmsg", msg.toString());
                }
            }
        });
        Map<String, List<LimsEnvironmentRoomBean>> groupByRoomCode = environmentRoomBeans.stream().filter(m -> !StringUtils.isBlank(m.getRoomCode())).collect(Collectors.groupingBy(LimsEnvironmentRoomBean::getRoomCode));

        List<LimsEnvironmentRoomBean> exists = limsEnvironmentRoomService.selectListByFilter(SearchFilter.instance().match("roomCode", new ArrayList<>(groupByRoomCode.keySet())).filter(MatchPattern.OR));
        groupByRoomCode.forEach((c, temp)->{
            List<LimsEnvironmentRoomBean> te=exists.stream().filter(e->c.equals(e.getRoomCode())).collect(Collectors.toList());
            if(te.isEmpty()){
                temp.forEach(a -> {
                    a.setExt$Item("validateimpmsg", "【房间号】不存在！");
                });
            }
        });

        // 返还校验结果
        if (environmentRoomBeans.stream().anyMatch(i -> !StringUtils.isEmpty(i.getExt$Item("validateimpmsg")))) {
            FilePathDTO filePathDTO = LimsExcelHelper.writeImportFailureListAsExcel(FilePathManager.getLocalPath(fr).toString(), environmentRoomBeans, 1, 2, "导入错误信息.xlsx", false);
            importResultRepresentation.setUrl(FilePathManager.getUrl(filePathDTO));
            importResultRepresentation.setMessage("导入失败");
            return importResultRepresentation;
        }

        List<String> idList = ApplicationContextHelper.getNextSequenceList(limsEnvironmentDataService.getDao().getTable(), environmentRoomBeans.size());
        final int[] i = {0};
        List<CoreCodeBean> codeBeans = coreCodeService.selectListByFilter(SearchFilter.instance().match("codeCategoryId", "materialType").filter(MatchPattern.EQ));
        List<LimsEnvironmentDataBean> limsEnvironmentDataBeans=new ArrayList<>();
        environmentRoomBeans.forEach(s -> {
            List<LimsEnvironmentRoomBean> temp=exists.stream().filter(e->s.getRoomCode().equals(e.getRoomCode())).collect(Collectors.toList());

            LimsEnvironmentDataBean dataBean=new LimsEnvironmentDataBean();
            dataBean.setId(NumberUtils.parseLong(idList.get(i[0])));
            dataBean.setRoomId(temp.get(0).getId());
            dataBean.setTempA(s.getExt$Item("tempA"));
            dataBean.setHumA(s.getExt$Item("tempA"));
            dataBean.setTime(LocalDateTime.parse(s.getExt$Item("time"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            dataBean.setRecA(s.getExt$Item("recA"));
            dataBean.setRemark(s.getExt$Item("remark"));

            limsEnvironmentDataBeans.add(dataBean);
            i[0]++;
        });
        limsEnvironmentDataService.getDao().insert(limsEnvironmentDataBeans);
        importResultRepresentation.setMessage("导入成功");
        return importResultRepresentation;
    }

    @Override
    public boolean test(CoreFileBean coreFile, String service) {
        return true;
    }
}
